import dataJson from '../db/index.json'

export interface Training {
  id: number
  title: string
  category: string
  price: string
  level: string
  duration: string
  durationRange: string
  equipment: string
  cover: string
}

export interface MyTraining {
  id?: number | string
  name: string
  level?: string
  equipments?: string[]
  parts?: string[]
  warmup?: boolean
  stretch?: boolean
  createdAt?: number
}

class DataService {
  private trainings: Training[] = dataJson.trainings
  private myTrainings: MyTraining[] = dataJson.mytrainings
  private myTrainingIdCounter = Math.max(...this.myTrainings.map(t => Number(t.id) || 0), 0) + 1

  // 训练课程相关方法
  getAllTrainings(): Training[] {
    return this.trainings
  }

  getTrainingById(id: number): Training | undefined {
    return this.trainings.find(t => t.id === id)
  }

  getTrainingsByCategory(category: string): Training[] {
    return this.trainings.filter(t => t.category === category)
  }

  getTrainingsByLevel(level: string): Training[] {
    return this.trainings.filter(t => t.level === level)
  }

  getFreeTrainings(): Training[] {
    return this.trainings.filter(t => t.price === '免费')
  }

  // 分类列表
  getCategories(): string[] {
    return [...new Set(this.trainings.map(t => t.category))]
  }

  // 我的训练计划相关方法
  getMyTrainings(): Promise<MyTraining[]> {
    return Promise.resolve([...this.myTrainings])
  }

  getMyTrainingById(id: string | number): Promise<MyTraining | undefined> {
    const training = this.myTrainings.find(t => t.id?.toString() === id.toString())
    return Promise.resolve(training)
  }

  createMyTraining(training: Omit<MyTraining, 'id' | 'createdAt'>): Promise<MyTraining> {
    const newTraining: MyTraining = {
      ...training,
      id: this.myTrainingIdCounter++,
      createdAt: Date.now()
    }
    this.myTrainings.push(newTraining)
    return Promise.resolve(newTraining)
  }

  deleteMyTraining(id: string | number): Promise<void> {
    const index = this.myTrainings.findIndex(t => t.id?.toString() === id.toString())
    if (index > -1) {
      this.myTrainings.splice(index, 1)
    }
    return Promise.resolve()
  }

  updateMyTraining(id: string | number, updates: Partial<MyTraining>): Promise<MyTraining | null> {
    const index = this.myTrainings.findIndex(t => t.id?.toString() === id.toString())
    if (index > -1) {
      this.myTrainings[index] = { ...this.myTrainings[index], ...updates }
      return Promise.resolve(this.myTrainings[index])
    }
    return Promise.resolve(null)
  }

  // 推荐算法
  getRecommendedTrainings(limit: number = 6): Training[] {
    // 简单的推荐逻辑：优先推荐免费课程，然后随机选择
    const freeTrainings = this.getFreeTrainings()
    const otherTrainings = this.trainings.filter(t => t.price !== '免费')
    
    // 使用Set确保ID唯一性
    const uniqueTrainings = new Map<number, Training>()
    
    // 先添加免费课程
    freeTrainings.forEach(training => {
      uniqueTrainings.set(training.id, training)
    })
    
    // 再添加其他课程
    otherTrainings.forEach(training => {
      if (!uniqueTrainings.has(training.id)) {
        uniqueTrainings.set(training.id, training)
      }
    })
    
    // 转换为数组并随机排序
    const shuffled = Array.from(uniqueTrainings.values())
      .sort(() => Math.random() - 0.5)
    
    return shuffled.slice(0, limit)
  }

  // 搜索功能
  searchTrainings(query: string): Training[] {
    const lowercaseQuery = query.toLowerCase()
    return this.trainings.filter(training => 
      training.title.toLowerCase().includes(lowercaseQuery) ||
      training.category.toLowerCase().includes(lowercaseQuery) ||
      training.equipment.toLowerCase().includes(lowercaseQuery)
    )
  }
}

// 导出单例实例
export const dataService = new DataService()
export default dataService
